package user

import (
	"context"
	"devops-super/internal/consts"
	"devops-super/internal/consts/cacheConsts"
	"devops-super/internal/dao"
	"devops-super/internal/model/entity"
	"devops-super/internal/service"
)

func (s *sUser) GetCurrentUser(ctx context.Context) (res *entity.User, err error) {
	userAuth := service.CurrentUser(ctx)
	return s.GetCacheUserById(ctx, int64(userAuth.UserId))
}

func (s *sUser) IsCurrentUserSuperAdmin(ctx context.Context) (res bool, currentUser *entity.User, err error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return false, user, err
	}
	if user == nil {
		return false, user, nil
	}
	if user.Id == consts.SuperUserId {
		return true, user, nil
	}
	return false, user, nil
}

func (s *sUser) IsCurrentUserSuperDept(ctx context.Context) (res bool, currentUser *entity.User, err error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return false, user, err
	}
	if user == nil {
		return false, user, nil
	}
	if user.DeptId == consts.SuperDeptId {
		return true, user, nil
	}
	return false, user, nil
}

func (s *sUser) GetCacheUserById(ctx context.Context, id int64) (out *entity.User, err error) {
	cacheKey := cacheConsts.GetUserInfo(id, consts.UserInfoKey)
	// 先从缓存获取
	if v, _ := service.GetCacheInstance().Get(ctx, cacheKey); !v.IsEmpty() {
		out = &entity.User{}
		if err = v.Struct(out); err == nil {
			return out, nil
		}
	}
	// 缓存未命中则查询数据库
	out = &entity.User{}
	err = dao.User.Ctx(ctx).Where(dao.User.Columns().Id, id).Scan(out)
	if err != nil {
		return nil, err
	}
	// 设置缓存
	_ = service.GetCacheInstance().Set(ctx, cacheKey, out, 0)
	return out, nil
}

func (s *sUser) RemoveUserInfoCache(ctx context.Context, id int64) (err error) {
	cacheKey := cacheConsts.GetUserInfo(id, consts.UserInfoKey)
	_, err = service.GetCacheInstance().Remove(ctx, cacheKey)
	return
}
